package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.itlong.cloud.POJO.DTO.app.AppElevatorAuthDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyHouseholdRoleAuthDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyHouseholdRoleGetPageDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyHouseholdRoleSaveDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.app.AppElevatorAuthVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.property.dao.IPropertyHouseholdRoleDao;
import com.itlong.cloud.property.service.IPropertyHouseholdRoleService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.string.StringUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *      物业系统住户权限(角色组)分配接口服务接口实现类
 * </desc>
 *
 * @createDate 2019/02/20
 */
@Service
public class PropertyHouseholdRoleServiceImpl implements IPropertyHouseholdRoleService {

    @Autowired
    private IPropertyHouseholdRoleDao iPropertyHouseholdRoleDao;


    /**
     * <desc>
     *      添加住户角色组信息
     * </desc>
     *
     * @param propertyHouseholdRoleSaveDTO 添加住户角色组信息数据DTO
     * @return 受影响的行数
     * @author wangzhi
     * @createDate 2019/02/20
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Map<String,String> saveHouseholdRole(PropertyHouseholdRoleSaveDTO propertyHouseholdRoleSaveDTO) throws Exception {
        Date nowTime = new Date();
        PropertyHouseholdRolePO propertyHouseholdRolePO = new PropertyHouseholdRolePO();
        propertyHouseholdRolePO.setRoleId(LogicIdUtil.bussinessId());
        propertyHouseholdRolePO.setProjectId(propertyHouseholdRoleSaveDTO.getProjectId());
        propertyHouseholdRolePO.setRoleName(propertyHouseholdRoleSaveDTO.getRoleName());
        propertyHouseholdRolePO.setStatus(propertyHouseholdRoleSaveDTO.getStatus());
        propertyHouseholdRolePO.setCreateTime(nowTime);
        propertyHouseholdRolePO.setUpdateTime(nowTime);
        iPropertyHouseholdRoleDao.save(SqlUtil.durableData(propertyHouseholdRolePO,PlatformConstants.TABLE_SAVE));
        Map<String,String> map = new HashMap<>();
        map.put("roleId",propertyHouseholdRolePO.getRoleId());
        return map;
    }

    /**
     * <desc>
     *      分页获取住户角色组信息
     * </desc>
     *
     * @param propertyHouseholdRoleGetPageDTO 添加住户角色组信息数据DTO
     * @return 分页结果
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyHouseholdRoleGetPageVO> getPage(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        if (propertyHouseholdRoleGetPageDTO.getOrderColumn() == null || propertyHouseholdRoleGetPageDTO.getOrderColumn().equals("")) {
            propertyHouseholdRoleGetPageDTO.setOrderColumn("create_time");
        }
        if (propertyHouseholdRoleGetPageDTO.getOrderRule() == null || propertyHouseholdRoleGetPageDTO.getOrderRule().equals("")) {
            propertyHouseholdRoleGetPageDTO.setOrderRule("desc");
        }
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyHouseholdRoleGetPageDTO);
        Page<PropertyHouseholdRoleGetPageVO> page = new Page<>();
        page.getPage().setPageSize(propertyHouseholdRoleGetPageDTO.getPageSize());
        page.getPage().setCurrentPage(propertyHouseholdRoleGetPageDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<PropertyHouseholdRoleGetPageVO> propertyHouseholdRoleGetPageVOS = iPropertyHouseholdRoleDao.getPage(params);
        page.setRows(propertyHouseholdRoleGetPageVOS, iPropertyHouseholdRoleDao.getRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      获取单个住户角色组信息
     * </desc>
     *
     * @param propertyHouseholdRoleGetPageDTO 添加住户角色组信息数据DTO
     * @return 单个住户角色组信息
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PropertyHouseholdRoleGetPageVO getOne(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyHouseholdRoleGetPageDTO);
        return iPropertyHouseholdRoleDao.getOne(params);
    }

    /**
     * <desc>
     *      修改住户角色组信息
     * </desc>
     *
     * @param propertyHouseholdRoleGetPageDTO 获取分页住户角色组信息DTO
     * @return 1-成功，0-失败
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer update(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        Date nowTime = new Date();
        PropertyHouseholdRolePO propertyHouseholdRolePO = new PropertyHouseholdRolePO();
        propertyHouseholdRolePO.setRoleId(propertyHouseholdRoleGetPageDTO.getRoleId());
        propertyHouseholdRolePO.setRoleName(propertyHouseholdRoleGetPageDTO.getRoleName());
        propertyHouseholdRolePO.setStatus(propertyHouseholdRoleGetPageDTO.getStatus());
        propertyHouseholdRolePO.setProjectId(null);
        propertyHouseholdRolePO.setUpdateTime(nowTime);
        Map<String,Object> map = SqlUtil.durableData(propertyHouseholdRolePO,PlatformConstants.TABLE_UPDATE);
        return iPropertyHouseholdRoleDao.update(map);
    }

    /**
     * <desc>
     *      校验住户角色组信息是否有关联数据
     * </desc>
     *
     * @param propertyHouseholdRoleGetPageDTO 获取分页住户角色组信息DTO
     * @return 1-有，0-无
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer checkRoleData(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        int userRoleCount = iPropertyHouseholdRoleDao.getUserRoleCount(propertyHouseholdRoleGetPageDTO.getRoleId(),propertyHouseholdRoleGetPageDTO.getProjectId());
        int entranceRoleCount = iPropertyHouseholdRoleDao.getEntranceRoleCount(propertyHouseholdRoleGetPageDTO.getRoleId(),propertyHouseholdRoleGetPageDTO.getProjectId());
        int elevatorRoleCount = iPropertyHouseholdRoleDao.getElevatorRoleCount(propertyHouseholdRoleGetPageDTO.getRoleId(),propertyHouseholdRoleGetPageDTO.getProjectId());
        if (userRoleCount + entranceRoleCount + elevatorRoleCount > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * <desc>
     *      删除住户角色组信息
     * </desc>
     *
     * @param propertyHouseholdRoleGetPageDTO 获取分页住户角色组信息DTO
     * @return 受影响行数
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer delete(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        iPropertyHouseholdRoleDao.deleteUserAuth(propertyHouseholdRoleGetPageDTO.getRoleId());
        iPropertyHouseholdRoleDao.deleteDeviceAuth(propertyHouseholdRoleGetPageDTO.getRoleId(),null);
        return iPropertyHouseholdRoleDao.delete(propertyHouseholdRoleGetPageDTO);
    }

    /**
     * <desc>
     *      分页获取门禁设备列表信息
     * </desc>
     *
     * @param propertyHouseholdRoleGetPageDTO 获取分页住户角色组信息DTO
     * @return 门禁设备列表信息
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyHouseholdRoleEntranceGetPageVO> getEntrancePage(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(propertyHouseholdRoleGetPageDTO);
        Page<PropertyHouseholdRoleEntranceGetPageVO> page = new Page<>();
        page.getPage().setPageSize(propertyHouseholdRoleGetPageDTO.getPageSize());
        page.getPage().setCurrentPage(propertyHouseholdRoleGetPageDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<PropertyHouseholdRoleEntranceGetPageVO> propertyHouseholdRoleEntranceGetPageVOS = iPropertyHouseholdRoleDao.getEntrancePage(params);
        page.setRows(propertyHouseholdRoleEntranceGetPageVOS, iPropertyHouseholdRoleDao.getEntranceRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      获取角色绑定的用户id列表
     * </desc>
     *
     * @param roleId 角色id
     * @return 用户id列表
     * @author wangzhi
     * @createDate 2019/02/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getUserIdListByRoleId(String roleId) throws Exception {
        return iPropertyHouseholdRoleDao.getUserIdListByRoleId(roleId);
    }

    /**
     * <desc>
     *      获取角色绑定的用户id列表,有人脸的用户
     * </desc>
     *
     * @param roleId 角色id
     * @param projectId 项目id
     * @return 用户id列表
     * @author Qiang.S
     * @createDate 2020/03/16
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getUserIdFaceListByRoleId(String roleId, String projectId) throws Exception {
        return iPropertyHouseholdRoleDao.getUserIdFaceListByRoleId(roleId,projectId);
    }

    /**
     * <desc>
     *      获取角色绑定的设备序列号列表
     * </desc>
     *
     * @param roleId 角色id
     * @param type 1为查询启用状态 2为非删除状态
     * @return 用户id列表
     * @author wangzhi
     * @createDate 2019/02/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getDeviceUniqueListByRoleId(String roleId,String type) throws Exception {
        List<String> roleIdList = StringHandlerUtil.splitStringList(roleId);
        return iPropertyHouseholdRoleDao.getDeviceUniqueListByRoleId(roleIdList,type);
    }

    /**
     * <desc>
     *      获取用户在非指定分组的设备序列号列表
     * </desc>
     *
     * @param roleId 角色id
     * @param userId 用户id
     * @param projectId 项目id
     * @return 设备列表
     * @author Juguang.S
     * @createDate 2021/04/02
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getEntranceListByNotInRoleIdAndUserId(String roleId,String userId,String projectId) throws Exception {
        return iPropertyHouseholdRoleDao.getEntranceListByNotInRoleIdAndUserId(roleId,userId,projectId);
    }


    /**
     * <desc>
     *      获取角色绑定的电梯设备序列号列表
     * </desc>
     *
     * @param roleId 角色id
     * @param type 1为查询启用状态 2为非删除状态
     * @return 用户id列表
     * @author Juguang.S
     * @createDate 2021/04/01
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Map<String,Object> getElevatorListByRoleId(String roleId,String type) throws Exception {
        List<String> roleIdList =StringHandlerUtil.splitStringList(roleId);
        List<AppElevatorAuthDTO> auth = iPropertyHouseholdRoleDao.getElevatorListByRoleId(roleIdList,type);
        if(auth.isEmpty()){
            return null;
        }
        List<String> deviceUniqueArr = new ArrayList<>();
        List<String> floorArr = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        AppElevatorAuthVO elevator = StringHandlerUtil.convertElevatorAuth(auth);
        String[] devices = StringHandlerUtil.splitString(elevator.getDeviceId());
        if (devices.length > 0) {
            elevator.getElevatorAuth().forEach(authInfo -> {
                deviceUniqueArr.add(auth.get(0).getProjectId()+"1"+authInfo.getDeviceId());
                floorArr.add(authInfo.getLiveFloor());
            });
            map.put("deviceUniqueArr",deviceUniqueArr);
            map.put("floorArr",floorArr);
            map.put("elevator",elevator);
        }
        return map;
    }

    /**
     * <desc>
     *      获取用户非指定分组外的电梯设备序列号列表
     * </desc>
     *
     * @param roleId 角色id
     * @param userId 用户id
     * @param projectId 项目id
     * @return 用户id列表
     * @author Juguang.S
     * @createDate 2021/04/02
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Map<String,Object> getElevatorListByNotInRoleIdAndUserId(String roleId,String userId,String projectId) throws Exception {
        List<AppElevatorAuthDTO> auth = iPropertyHouseholdRoleDao.getElevatorListByNotInRoleIdAndUserId(roleId,userId,projectId);
        if(auth.isEmpty()){
            return null;
        }
        List<String> deviceUniqueArr = new ArrayList<>();
        List<String> floorArr = new ArrayList<>();
        Map<String,Object> returnMap = new HashMap<>();
        Map<String,String> map = new HashMap<>();
        AppElevatorAuthVO elevator = StringHandlerUtil.convertElevatorAuth(auth);
        String[] devices = StringHandlerUtil.splitString(elevator.getDeviceId());
        if (devices.length > 0) {
            elevator.getElevatorAuth().forEach(authInfo -> {
                if(map.containsKey(authInfo.getDeviceId())){
                    String deviceId = map.get(authInfo.getDeviceId())+","+authInfo.getLiveFloor();
                    map.put(authInfo.getDeviceId(),deviceId);
                }else{
                    map.put(authInfo.getDeviceId(),authInfo.getLiveFloor());
                }
                deviceUniqueArr.add(auth.get(0).getProjectId()+"1"+authInfo.getDeviceId());
                floorArr.add(map.get(authInfo.getDeviceId()));
            });
            returnMap.put("deviceUniqueArr",deviceUniqueArr);
            returnMap.put("floorArr",floorArr);
            returnMap.put("elevator",elevator);
        }
        return returnMap;
    }

    /**
     * <desc>
     *      住户角色组信息设备授权
     * </desc>
     *
     * @return 0-失败 1-成功
     * @author wangzhi
     * @createDate 2019/02/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer deviceAuth(PropertyHouseholdRoleAuthDTO propertyHouseholdRoleAuthDTO) throws Exception {

        switch (PropertyEquipTypeEnum.getByEquipType(propertyHouseholdRoleAuthDTO.getDeviceType())){
            case ELEVATOR:

                Map<String, String> elevatorFloorMap = new HashMap<>();
                //获取有权限的电梯
                Map<String, Object> elevatorAuthMap = iPropertyHouseholdRoleDao.getElevatorAuthByGroupId(propertyHouseholdRoleAuthDTO.getRoleId());
                Map<String, String> elevatorFloorAuthMap = StringHandlerUtil.assembleElevatorAuth(elevatorAuthMap, propertyHouseholdRoleAuthDTO.getProjectId());
                if(elevatorFloorAuthMap != null && elevatorFloorAuthMap.keySet().size() > 0){
                    String[] deviceUniqueArr = StringHandlerUtil.splitString(propertyHouseholdRoleAuthDTO.getCurrentDeviceUniques());
                    for(String deviceUnique : deviceUniqueArr){
                        if(elevatorFloorAuthMap.containsKey(deviceUnique)){
                            elevatorFloorAuthMap.remove(deviceUnique);
                        }
                    }
                    elevatorFloorMap.putAll(elevatorFloorAuthMap);
                }
                //删除电梯与原住户分组权限关系
                iPropertyHouseholdRoleDao.deleteGroupElevatorAuth(propertyHouseholdRoleAuthDTO.getRoleId());
                List<String> selectDeviceList = StringHandlerUtil.splitStringList(propertyHouseholdRoleAuthDTO.getDeviceUniques());
                List<String> naturalFloorList = JSON.parseArray(propertyHouseholdRoleAuthDTO.getNaturalFloors(), String.class);

                for (int i = selectDeviceList.size()-1; i>=0; i--){
                    elevatorFloorMap.put(selectDeviceList.get(i), naturalFloorList.get(i));
                }
                DeviceElevatorGroupInfoPO deviceElevatorGroupInfoPO = this.convertNewTmpElevatorAuthToMapToPO(elevatorFloorMap);
                deviceElevatorGroupInfoPO.setGroupId(propertyHouseholdRoleAuthDTO.getRoleId());
                deviceElevatorGroupInfoPO.setProjectId(propertyHouseholdRoleAuthDTO.getProjectId());
                deviceElevatorGroupInfoPO.setRelationId(LogicIdUtil.bussinessId());
                deviceElevatorGroupInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                deviceElevatorGroupInfoPO.setCreateTime(new Date());
                deviceElevatorGroupInfoPO.setUpdateTime(new Date());
                iPropertyHouseholdRoleDao.save(SqlUtil.durableData(deviceElevatorGroupInfoPO, PlatformConstants.TABLE_SAVE));

                break;
            case ENTRANCE:
                iPropertyHouseholdRoleDao.deleteDeviceAuth(propertyHouseholdRoleAuthDTO.getRoleId(),StringHandlerUtil.splitString(propertyHouseholdRoleAuthDTO.getCurrentDeviceUniques()));
                if (StringUtils.isNotBlank(propertyHouseholdRoleAuthDTO.getDeviceUniques())) {
                    List<String> deviceUniques = StringHandlerUtil.splitStringList(propertyHouseholdRoleAuthDTO.getDeviceUniques());
                    //查询角色下的设备机号 若有则不保存
                    List<String> roleIdList= new ArrayList<>();
                    roleIdList.add(propertyHouseholdRoleAuthDTO.getRoleId());
                    List<String> entranceArr = iPropertyHouseholdRoleDao.getDeviceUniqueListByRoleId(roleIdList,"1");
                    Date nowTime = new Date();
                    List<DeviceEntranceRolePO> deviceEntranceRolePOList = new ArrayList<>();
                    for (String deviceUnique : deviceUniques) {
                        if(entranceArr!=null && entranceArr.size()>0 && entranceArr.contains(deviceUnique)){
                            continue;
                        }
                        DeviceEntranceRolePO deviceEntranceRolePO = new DeviceEntranceRolePO();
                        deviceEntranceRolePO.setDeviceUnique(deviceUnique);
                        deviceEntranceRolePO.setRoleId(propertyHouseholdRoleAuthDTO.getRoleId());
                        deviceEntranceRolePO.setStatus(DataStatusEnum.NORMAL.getType());
                        deviceEntranceRolePO.setCreateTime(nowTime);
                        deviceEntranceRolePO.setUpdateTime(nowTime);
                        deviceEntranceRolePOList.add(deviceEntranceRolePO);
                    }
                    if(deviceEntranceRolePOList!=null && deviceEntranceRolePOList.size()>0){
                        iPropertyHouseholdRoleDao.batchSaveDeviceAuth(deviceEntranceRolePOList);
                    }
                }
                break;
        }


        return 1;
    }

    /**
     * <desc>
     *      住户角色组信息人员分配
     * </desc>
     *
     * @return 0-失败 1-成功
     * @author wangzhi
     * @createDate 2019/02/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer userAuth(PropertyHouseholdRoleAuthDTO propertyHouseholdRoleAuthDTO) throws Exception {
        iPropertyHouseholdRoleDao.deleteUserAuth(propertyHouseholdRoleAuthDTO.getRoleId());
        if (StringUtils.isNotBlank(propertyHouseholdRoleAuthDTO.getUserIds())) {
            List<String> userIds = StringHandlerUtil.splitStringList(propertyHouseholdRoleAuthDTO.getUserIds());
            Date nowTime = new Date();
            List<AppUserEntranceRolePO> appUserEntranceRolePOList = new ArrayList<>();
            for (String userId : userIds) {
                AppUserEntranceRolePO appUserEntranceRolePO = new AppUserEntranceRolePO();
                appUserEntranceRolePO.setUserId(userId);
                appUserEntranceRolePO.setRoleId(propertyHouseholdRoleAuthDTO.getRoleId());
                appUserEntranceRolePO.setStatus(DataStatusEnum.NORMAL.getType());
                appUserEntranceRolePO.setCreateTime(nowTime);
                appUserEntranceRolePO.setUpdateTime(nowTime);
                appUserEntranceRolePOList.add(appUserEntranceRolePO);
            }
            return iPropertyHouseholdRoleDao.batchSaveUserAuth(appUserEntranceRolePOList);
        }
        return 1;
    }

    /**
     * <desc>
     *      拿到当前角色id所有普通门禁设备序列号字符串
     * </desc>
     *
     * @return 所有普通门禁设备序列号字符串
     * @author wangzhi
     * @createDate 2019/02/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String getAllDeviceUniqueStr(String projectId) throws Exception {
        return iPropertyHouseholdRoleDao.getAllDeviceUniqueStr(projectId);
    }

    /**
     *<desc>
     *      根据项目编号查询所有的电梯设备
     *</desc>
     *
     * @return 所有的电梯设备序列号字符串
     * @author Juguang.S
     * @createDate 2021/04/01
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String getAllElevatorDeviceUniqueStr(String projectId) throws Exception {
        return iPropertyHouseholdRoleDao.getAllElevatorDeviceUniqueStr(projectId);
    }

    /**
     *<desc>
     *      过滤有人脸的用户
     *</desc>
     *
     * @param userIds 用户id
     * @param projectId 项目id
     * @return
     * @author Qiang.S
     * @createDate 2020/03/16
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getUserHaveFace(List<String> userIds, String projectId) throws Exception {
        return iPropertyHouseholdRoleDao.getUserHaveFace(userIds,projectId);
    }

    /**
     * <desc>
     *      获取电梯分页列表
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/3/29
     */
    @Override
    public Page<PropertyHouseHoldRoleElevatorGetPageVO> getElevatorPage(PropertyHouseholdRoleGetPageDTO propertyHouseholdRoleGetPageDTO) throws Exception {
        Page<PropertyHouseHoldRoleElevatorGetPageVO> page = new Page<>();
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(propertyHouseholdRoleGetPageDTO);
        page.getPage().setCurrentPage(propertyHouseholdRoleGetPageDTO.getCurrentPage());
        page.getPage().setPageSize(propertyHouseholdRoleGetPageDTO.getPageSize());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());



        //获取有权限的电梯
        Map<String, Object> elevatorAuthMap = iPropertyHouseholdRoleDao.getElevatorAuthByGroupId(propertyHouseholdRoleGetPageDTO.getRoleId());
        Map<String, String> elevatorFloorAuthMap = StringHandlerUtil.assembleElevatorAuth(elevatorAuthMap, propertyHouseholdRoleGetPageDTO.getProjectId());
        if(elevatorFloorAuthMap != null && elevatorFloorAuthMap.keySet().size() > 0){
            Set<String> deviceUniqueSet = elevatorFloorAuthMap.keySet();
            params.put("deviceUniques", deviceUniqueSet);
        }
        //根据传入的角色组名称找出角色组下的电梯
        if (StringUtils.isNotBlank(propertyHouseholdRoleGetPageDTO.getRoleName())){

            String roleId = iPropertyHouseholdRoleDao.getRoleIdByRoleName(params);
            List<Map<String, Object>> roleElevatorAuthMapList = iPropertyHouseholdRoleDao.getElevatorAuthByGroupIds(roleId);
            Set<String> deviceUniqueSet = new HashSet<>();
            for (Map<String, Object> roleElevatorAuthMap : roleElevatorAuthMapList){
                Map<String, String> roleElevatorFloorAuthMap = StringHandlerUtil.assembleElevatorAuth(roleElevatorAuthMap, propertyHouseholdRoleGetPageDTO.getProjectId());
                if (roleElevatorFloorAuthMap != null && roleElevatorFloorAuthMap.keySet().size() > 0){
                    deviceUniqueSet.addAll(roleElevatorFloorAuthMap.keySet());
                }
            }
            if (!deviceUniqueSet.isEmpty()){
                params.put("roleDeviceUniques", deviceUniqueSet);
            }
        }

        //获取电梯的角色组
        Map<String, String> elevatorGroups = this.getElevatorGroup(propertyHouseholdRoleGetPageDTO.getProjectId());

        List<PropertyHouseHoldRoleElevatorGetPageVO> getPageVOS = iPropertyHouseholdRoleDao.getElevatorPage(params);
        Integer pageVOSCount = iPropertyHouseholdRoleDao.getElevatorPageCount(params);
        for (PropertyHouseHoldRoleElevatorGetPageVO getPageVO : getPageVOS){
            //设置楼层权限
            getPageVO.setPropertyElevatorFloorVOS(this.handlerFloorConfig(getPageVO, elevatorFloorAuthMap));
            //将同一群控器下的电梯分组展示
            getPageVO.setDeviceGroups(this.handlerControllerDevice(getPageVO));
            //获取电梯的地址（通过getPageVO.getDeviceUnique）
            getPageVO.setEquipAddress(iPropertyHouseholdRoleDao.getElevatorAddress(getPageVO.getDeviceUnique()));

            if (elevatorFloorAuthMap != null && elevatorFloorAuthMap.get(getPageVO.getDeviceUnique()) != null){
                //拼接楼层权限，让前端展示
                getPageVO.setFloors(elevatorFloorAuthMap.get(getPageVO.getDeviceUnique()));
                getPageVO.setIsChecked(Integer.toString(PlatformConstants.DEVICEAUTH_ISCHECKED_YSE));
            }else {
                getPageVO.setIsChecked(Integer.toString(PlatformConstants.DEVICEAUTH_ISCHECKED_YET));
            }

            //修改同一群控器下设备所属的角色组
            if (elevatorGroups != null && elevatorGroups.get(getPageVO.getDeviceUnique())!= null){
                getPageVO.getDeviceGroups().forEach(item ->{
                    item.setRoleName(elevatorGroups.get(getPageVO.getDeviceUnique()));
                });
            }
        }
        page.setRows(getPageVOS, pageVOSCount);

        return page;
    }

    /**
     * <desc>
     *      校验输入的用户分组是否合法
     * </desc>
     *
     * @param userGroups 用户分组逗号拼接字符串
     * @return 分组id列表
     * @Author Zhu.yj
     * @createDate  2021/4/9
     */
    @Override
    public List<String> checkUserGroupExist(String userGroups, String projectId) throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<String> userGroupList = new ArrayList<>();
        List<String> userGroupAllList = StringHandlerUtil.splitStringList(userGroups);
        //去除传入的空字符串
        for (String userGroup : userGroupAllList){
            if (StringUtils.isNotBlank(userGroup)){
                userGroupList.add(userGroup);
            }
        }
        params.put("userGroupList", userGroupList);
        params.put("projectId", projectId);
        return iPropertyHouseholdRoleDao.getUserGroupCount(params);
    }

    /**
     * <desc>
     *      删除用户权限
     * </desc>
     *
     * @param userId 用户id
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/13
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer deleteUserDeviceAuth(String userId, String projectId) throws Exception {

        //删除电梯权限

        //删除门禁权限

        return null;
    }

    /**
     * <desc>
     *      用户角色组授权
     * </desc>
     *
     * @param propertyHouseholdRoleAuthDTO 用户及角色组传参
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/22
     */
    @Override
    public Integer userRoleGroupAuth(PropertyHouseholdRoleAuthDTO propertyHouseholdRoleAuthDTO) throws Exception {
        //删除用户旧的角色分组
        Map<String, Object> params= new HashMap<>();
        Date nowTime = new Date();
        List<AppUserEntranceRolePO> appUserEntranceRolePOList = new ArrayList<>();
        List<String> roleIdList= StringHandlerUtil.splitStringList(propertyHouseholdRoleAuthDTO.getRoleId());
        params.put("projectId", propertyHouseholdRoleAuthDTO.getProjectId());
        params.put("userId", propertyHouseholdRoleAuthDTO.getUserIds());
        iPropertyHouseholdRoleDao.deleteUserGroup(params);

        //保存新的角色分组
        if (!roleIdList.isEmpty()){
            for (String roleId : roleIdList) {
                AppUserEntranceRolePO appUserEntranceRolePO = new AppUserEntranceRolePO();
                appUserEntranceRolePO.setUserId(propertyHouseholdRoleAuthDTO.getUserIds());
                appUserEntranceRolePO.setRoleId(roleId);
                appUserEntranceRolePO.setStatus(DataStatusEnum.NORMAL.getType());
                appUserEntranceRolePO.setCreateTime(nowTime);
                appUserEntranceRolePO.setUpdateTime(nowTime);
                appUserEntranceRolePOList.add(appUserEntranceRolePO);
            }
            return iPropertyHouseholdRoleDao.batchSaveUserAuth(appUserEntranceRolePOList);
        }
        return 0;
    }

    /**
     * <desc>
     *      获取指定电梯所绑定群控器下的所有电梯
     * </desc>
     *
     * @param deviceUnique 电梯唯一编码
     * @return 电梯机号
     * @Author Juguang.S
     * @createDate  2021/5/10
     */
    @Override
    public List<String> getCloudControllerElevatorInfo(String deviceUnique) throws Exception {
        return iPropertyHouseholdRoleDao.getCloudControllerElevatorInfo(deviceUnique);
    }

    /**
     * <desc>
     *      获取同一群控器下绑定的电梯
     * </desc>
     *
     * @param currentDeviceUniques 当前页所有设备唯一码
     * @return
     * @Author Zhu.yj
     * @createDate  2021/5/17
     */
    @Override
    public String getDeviceUniqueIdList(String currentDeviceUniques, String projectId) throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<String> deviceUniqueList = StringHandlerUtil.splitStringList(currentDeviceUniques);
        params.put("deviceUniqueList", deviceUniqueList);
        params.put("projectId", projectId);
        List<String> deviceUniques =  iPropertyHouseholdRoleDao.getDeviceUniqueIdList(params);
        deviceUniques.addAll(deviceUniqueList);
        Set<String> deviceUniqueSet = new HashSet<>(deviceUniques);
        StringBuilder stringBuilder = new StringBuilder();

        for (String deviceUnique : deviceUniqueSet){
            stringBuilder.append(deviceUnique).append(",");
        }
        return stringBuilder.substring(0, stringBuilder.length() -1);
    }


    /**
     * <desc>
     *      处理绑定同一群控器的电梯分组展示
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/3/30
     */
    private List<PropertyDeviceUserGroupVO> handlerControllerDevice(PropertyHouseHoldRoleElevatorGetPageVO getPageVO){
        //将同一群控器下的电梯分组展示
        List<PropertyDeviceUserGroupVO> userGroupVOList = new ArrayList<>();
        List<String> deviceUniqueList = StringHandlerUtil.splitStringList(getPageVO.getDeviceUniques());
        List<String> deviceNameList = StringHandlerUtil.splitStringList(getPageVO.getDeviceNames());

        for (int i = 0; i< deviceUniqueList.size(); i++){
            PropertyDeviceUserGroupVO userGroupVO = new PropertyDeviceUserGroupVO();
            userGroupVO.setDeviceName(deviceNameList.get(i));
            userGroupVO.setDeviceUnique(deviceUniqueList.get(i));
            userGroupVO.setDeviceId(deviceUniqueList.get(i).substring(9, 13));
            userGroupVOList.add(userGroupVO);
        }
        return userGroupVOList;
    }

    /**
     * <desc>
     *      处理电梯楼层映射表配置
     * </desc>
     *
     * @param getPageVO
     * @return List<PropertyElevatorFloorVO> 前端展示的楼层信息
     * @Author Zhu.yj
     * @createDate  2021/3/31
     */
    private List<PropertyElevatorFloorVO> handlerFloorConfig(PropertyHouseHoldRoleElevatorGetPageVO getPageVO, Map<String, String> elevatorFloorAuthMap){
        Map<String, Object> param = new HashMap<>();
        param.put("deviceUnique", getPageVO.getDeviceUnique());
        if (getPageVO.getFloorNo() != null && getPageVO.getFloorNoMax() != null) {
            param.put("floorNo", getPageVO.getFloorNo());
            param.put("floorNoMax", getPageVO.getFloorNoMax());
        }
        //获取电梯楼层映射表信息
        List<DeviceElevatorFloorConfigPO> floorConfigPOS = iPropertyHouseholdRoleDao.getShowFloor(param);
        List<PropertyElevatorFloorVO> floorVOS = new ArrayList<>();
        for (DeviceElevatorFloorConfigPO floorConfigPO : floorConfigPOS){
            PropertyElevatorFloorVO floorVO = new PropertyElevatorFloorVO();
            floorVO.setDeviceUnique(getPageVO.getDeviceUnique());
            floorVO.setFloorName(floorConfigPO.getLogicalFloor());
            floorVO.setNaturalFloor(floorConfigPO.getNaturalFloor());
            if (elevatorFloorAuthMap != null){
                List<String> authFloor = StringHandlerUtil.splitStringList(elevatorFloorAuthMap.get(floorConfigPO.getDeviceUnique()));
                //无该电梯权限或无该电梯楼层权限
                if (authFloor == null || !authFloor.contains(floorConfigPO.getNaturalFloor())){
                    //
                    floorVO.setIsChecked(Integer.toString(PlatformConstants.DEVICEAUTH_ISCHECKED_YET));
                }else{
                    floorVO.setIsChecked(Integer.toString(PlatformConstants.DEVICEAUTH_ISCHECKED_YSE));
                }
            }else {
                floorVO.setIsChecked(Integer.toString(PlatformConstants.DEVICEAUTH_ISCHECKED_YET));
            }

            floorVOS.add(floorVO);
        }
        return floorVOS;
    }

    /**
     * <desc>
     *     将设备权限Map.<deviceUnique,floorHexStr> eg <0000031210001,4000000000000000000000000000>转换为存库对象
     * </desc>
     *
     * @param newTmpElevatorAuthMap 设备权限Map.<deviceUnique,floorHexStr> eg <0000031210001,4000000000000000000000000000>
     * @return 物业临时电梯权限数据库对象
     * @author LewisLouis
     * @createDate 2018-01-03
     */
    private DeviceElevatorGroupInfoPO convertNewTmpElevatorAuthToMapToPO(Map<String,String> newTmpElevatorAuthMap){
        Map<String, String> orderedElevatorAuthMapMap = new TreeMap<>(newTmpElevatorAuthMap);
        String binDeviceAuth = StringHandlerUtil.fillString(PlatformConstants.ELEVATOR_NOAUTHNUM,PlatformConstants.ELEVATOR_NOAUTHNUM,PlatformConstants.MAX_ELEVATOR_DEVICEID);
        StringBuilder binDeviceAuthBuffer = new StringBuilder(binDeviceAuth);
        List<String> floorsList = new ArrayList<>();
        for (Map.Entry<String, String> entry : orderedElevatorAuthMapMap.entrySet()) {
            String deviceUnique = entry.getKey();
            Integer devId = StringHandlerUtil.
                    strToIntDef(StringHandlerUtil.copySubStr(deviceUnique,9,4),0);
            //设备在授权设备信息字符串中的位置
            int deviceAuthIndex = devId  -  1;
            binDeviceAuthBuffer.setCharAt(deviceAuthIndex, PlatformConstants.ELEVATOR_AUTHNUM.charAt(0));
            StringBuffer floorAuth = new StringBuffer(entry.getValue());
            String hexFloorAuth = StringHandlerUtil.getAuthCodeBynNturalFloors(StringHandlerUtil.clearComma(floorAuth).toString());
            floorsList.add(hexFloorAuth);
        }
        String floorsAuth = Joiner.on(",").join(floorsList);
        DeviceElevatorGroupInfoPO deviceElevatorGroupInfoPO = new DeviceElevatorGroupInfoPO();
        deviceElevatorGroupInfoPO.setDeviceAuth(binDeviceAuthBuffer.toString());
        deviceElevatorGroupInfoPO.setFloorAuth(floorsAuth);
        return deviceElevatorGroupInfoPO;
    }

    /**
     * <desc>
     *      根据从数据库中取出的groupId,elevatorAuth(1,00000000000000000000100111111),转换为(deviceUnique,groupId)
     * </desc>
     *
     * @param projectId 项目id
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/1
     */
    private Map<String, String> getElevatorGroup(String projectId){
        Map<String, String> deviceGroups = new HashMap<>();
        Map<String, String> returnDeviceGroup = new HashMap<>();
        //找出所有角色组下的电梯，再转换成电梯拥有的角色组
        List<Map<String, String>> groupDevices = iPropertyHouseholdRoleDao.getGroupDevice(projectId);
        for (int i = 0; i< groupDevices.size(); i++){
            deviceGroups.put(groupDevices.get(i).get("groupName"), groupDevices.get(i).get("deviceAuth"));
        }

        for (Map.Entry entry : deviceGroups.entrySet()){
            List<String> deviceIdList = StringHandlerUtil.splitStringList(StringHandlerUtil.convertAuth(entry.getValue().toString(), "1"));
            for (String deviceId : deviceIdList){
                String deviceUnqiue = projectId + PropertyEquipTypeEnum.ELEVATOR.getType() + deviceId;
                if (returnDeviceGroup.get(deviceUnqiue) != null){
                    returnDeviceGroup.put(deviceUnqiue, returnDeviceGroup.get(deviceUnqiue) +"," + entry.getKey());
                }else {
                    returnDeviceGroup.put(deviceUnqiue, entry.getKey().toString());
                }
            }
        }
        return returnDeviceGroup;
    }

}
